<template>
  <div v-loading="loading" class="ins_box">
    <div class="ins_content">
      <flex class="tabs">
        <div
          :class="{ select: activeIndex === item.value }"
          class="temp-item"
          v-for="item in tabList"
          :key="item.value"
          @click="handleSelect(item)"
        >
          {{ item.content }}
        </div>
      </flex>
      <div class="ins-input">
        <div class="main-scroll">
          <el-input
            v-model.trim="insValue"
            :title="insValue"
            :rows="32"
            :show-word-limit="false"
            type="textarea"
            :placeholder="'请先选中要' + isContent + '的文本内容再开始'"
            style="width: 100%"
            resize="none"
            clearable
          />
        </div>
      </div>
    </div>
    <flex
      class="ins_button_list"
      align="center"
      justify="center"
      direction="column"
    >
      <div>
        <el-button
          v-for="(btn, index) in buttonList"
          :key="btn.value + index"
          :type="btn.type"
          size="mini"
          @click="handleIns(btn)"
        >
          {{ isFirst ? btn.name : btn.alias || btn.name }}
        </el-button>
      </div>
      <div :class="'tips'" v-if="!isSlectText">
        请先选中文本内容再执行{{ isContent }}！
      </div>
    </flex>
  </div>
</template>

<script>
// import * as api from '@/api/writing'
import Axios from 'axios'
export default {
  data() {
    return {
      loading: false,
      isFirst: true,

      insValue: '',
      buttonList: [
        {
          value: 'polish',
          type: 'primary',
          name: '润色',
          alias: '重写',
        },
        {
          value: 'copy',
          type: 'default',
          name: '复制',
        },
        {
          value: 'replace',
          type: 'default',
          name: '替换',
        },
        {
          value: 'clear',
          type: 'default',
          name: '清空',
        },
      ],

      isSlectText: false, //是否选中文本

      activeIndex: 1,
      isContent: '润色',
      tabList: [
        {
          content: '润色',
          value: 1,
        },
        {
          content: '扩写',
          value: 2,
        },
        {
          content: '改写',
          value: 3,
        },
        {
          content: '缩写',
          value: 4,
        },
        {
          content: '续写',
          value: 5,
        },
        {
          content: '仿写',
          value: 6,
        },
      ],
    }
  },
  methods: {
    handleSelect(item) {
      this.activeIndex = item.value
      this.isContent = item.content
      this.insValue = ''

      //
      this.buttonList.map((it, idx) => {
        if (idx === 0) {
          it.name = this.isContent
        }
        //续写
        if (item.content === '续写' && idx === 2) {
          it.name = '插入'
        } else if (idx === 2) {
          it.name = '替换'
        }
      })
    },

    //点击底部执行事件
    handleIns(btn) {
      const value = btn.value
      switch (value) {
        case 'polish':
          this.handlePolish()
          break
        case 'copy':
          this.handleCopy()
          break
        case 'replace':
          try {
            let rangeObj = JSON.parse(window.c_methods.getNowRange())
            let range = rangeObj.data || null
            // window.alert(JSON.stringify(range))
            // 是否选择了内容 Type: 2(标准的或用户定义的选择内容)
            if (range) {
              if (!this.insValue) {
                this.$message.warning('暂无可替换内容！')
                return
              }
              if (this.isContent !== '续写') {
                // 非续写直接替换选中的位置内容
                window.c_methods.replaceRangeText(
                  range.start,
                  range.end,
                  this.insValue
                )
                this.$message.success('替换成功')
              } else {
                //续写在后面插入
                //获取选中的文本内容
                let rangTextObj = JSON.parse(
                  window.c_methods.getRangeText(range.start, range.end)
                ).data
                if (rangTextObj) {
                  // window.alert(rangTextObj)
                  window.c_methods.replaceRangeText(
                    range.start + rangTextObj.length,
                    range.end,
                    this.insValue
                  )
                } else {
                  window.c_methods.replaceRangeText(
                    range.start,
                    range.end,
                    this.insValue
                  )
                }
                this.$message.success('插入成功')
              }
            } else {
              // this.$message.warning('请选择文本内容！')
              this.$notify.warning({
                title: '选中文本',
                message: `请先选中文本内容再执行${this.isContent}！`,
              })
            }
          } catch (error) {}
          break

        case 'clear':
          this.insValue = ''
          this.$message.success('清空成功')
          break

        default:
          break
      }
    },
    // 润色
    handlePolish() {
      try {
        let rangeObj = JSON.parse(window.c_methods.getNowRange())
        let range = rangeObj.data || null
        // window.alert(JSON.stringify(range))
        let rangTextObj = JSON.parse(
          window.c_methods.getRangeText(range.start, range.end)
        ).data
        // window.alert(rangTextObj)
        // 是否选择了内容 Type: 2(标准的或用户定义的选择内容)
        if (range && rangTextObj) {
          this.isSlectText = true
          this.loading = true
          var data = JSON.stringify({
            model: '',
            stream: false,
            max_tokens: 4000,
            messages: [
              {
                role: 'user',
                content: this.isContent,
                text: rangTextObj,
              },
            ],
          })
          var config = {
            method: 'post',
            url: 'http://gwdmx.dacube.com.cn/',
            headers: {
              Authorization: 'Basic Z3B1YXBpOnEjYmU3N0xlalZzMDE=',
              'Content-Type': 'application/json',
            },
            data: data,
          }
          var _this = this
          Axios(config)
            .then(function (response) {
              if (response && response.data && response.data.choices[0]) {
                let text = response.data.choices[0].message.content
                // window.alert(text)
                _this.insValue = text
              }
            })
            .catch(function (error) {
              this.$notify.error('接口异常,稍后再试！')
              console.log(error)
            })
            .finally(() => {
              this.loading = false
            })
          
        } else {
          this.isSlectText = false
          // this.$message.warning('请选择文本内容！')
          this.$notify.warning({
            title: '选中文本',
            message: '请先选中文本内容再执行！',
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 复制
    handleCopy() {
      if (!this.insValue) {
        this.$message.warning('无内容可复制！')
        return
      }
      let input = document.createElement('input')
      input.setAttribute('value', this.insValue)
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      document.body.removeChild(input)
      this.$message.success('复制成功')
    },
  },
}
</script>

<style scoped>
.ins_box {
  position: relative;
}
.ins_content {
  padding: 10px;
  height: calc(100% - 90px);
}
.tabs {
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  background-color: #fff;
}
.temp-item {
  cursor: pointer;
  padding: 8px 0px;
  color: #606166;
  font-size: 15px;
  text-align: center;
  font-weight: 500;
  flex: 1;
  /* border: 1px solid #efeff1; */
  border-right: 1px solid #efeff1;
  border-bottom-width: 0;
}

.temp-item:first-child {
  border-top-left-radius: 8px;
  box-shadow: -10px 0 10px -5px rgba(0, 0, 0, 0.03);
}
.temp-item:last-child {
  border-top-right-radius: 8px;
  border-right: none;
  box-shadow: 10px 0 10px -5px rgba(0, 0, 0, 0.03);
}
.temp-item:hover {
  color: #606166;
}
.temp-item.select {
  color: #fff;
  background-color: rgb(53, 125, 255);
}
.ins-input {
  padding: 10px;
  height: calc(100% - 90px);
  width: 100%;
  overflow: hidden;
  box-sizing: border-box;
  background-color: #fff;
  border-radius: 0px 0px 6px 6px;
  box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.15);
}
.ins-input .main-scroll {
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
}

.ins-input >>> .el-textarea__inner {
  font-family: Arial;
  background-color: #fafafa;
}
.ins-input >>> .el-textarea__inner:focus {
  background-color: #fff;
}
.ins_button_list {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 90px;
  background-color: #fff;
  border-radius: 0 0 6px 0;
  box-shadow: 2px 0 4px 0 rgba(0, 0, 0, 0.2);
}
.ins_button_list .el-button + .el-button {
  margin-left: 10px;
}
.ins_button_list .tips {
  font-size: 12px;
  margin-top: 10px;
  color: #eb444b;
  width: 100%;
  background: rgba(53, 125, 255, 0.05);
  text-align: center;
  padding: 6px 0px;
}
</style>
